define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'template'], function ($, undefined, Backend, Table, Form, Template) {

    var Controller = {
        index: function () 
        {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'depot/back/index',
                    add_url: 'depot/back/add',
                    edit_url: 'depot/back/edit',
                    del_url: 'depot/back/del',
                    info_url: 'depot/back/info',
                    agree_url: 'depot/back/agree',
                    reject_url: 'depot/back/reject',
                    receipt_url: 'depot/back/receipt',
                    revoke_url: 'depot/back/revoke',
                    table: 'depot_back',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                onLoadSuccess:function()
                {
                    $('.btn-editone').data('area',['100%','100%'])
                    $(".btn-add,.btn-edit").data("area", ["80%", "100%"]);
                },
                columns: [
                    [
                        {field: 'id', title: __('Id')},
                        {field: 'code', title: __('Code'), operate: 'LIKE'},
                        {field: 'ordercode', title: __('Ordercode'), operate: 'LIKE'},
                        {field: 'business.nickname', title: __('Busid')},
                        {field: 'contact', title: __('Contact'), operate: 'LIKE'},
                        {field: 'phone', title: __('Phone'), operate: 'LIKE'},
                        {field: 'amount', title: __('Amount'), operate:'BETWEEN'},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'status', title: __('Status'), searchList: Config.statuslist, formatter: Table.api.formatter.status},
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate,
                            buttons: [
                                {
                                    name:'info',
                                    title:'详情',
                                    classname:'btn btn-xs btn-success btn-dialog',
                                    extend: 'data-toggle=\'tooltip\' data-area= \'["80%", "80%"]\'', //重点是这一句
                                    url:$.fn.bootstrapTable.defaults.extend.info_url,
                                    icon:'fa fa-eye'
                                },
                                {
                                    name:'agree',
                                    title:'通过审核',
                                    classname:'btn btn-xs btn-success btn-ajax',
                                    extend: 'data-toggle=\"tooltip\"data-container=\"body\"',
                                    icon:'fa fa-check',
                                    confirm:'确认通过审核吗？',
                                    url: $.fn.bootstrapTable.defaults.extend.agree_url,
                                    success: data => $(".btn-refresh").trigger("click"),
                                    visible: row => row.status == 0 ? true : false,
                                },
                                {
                                    name:'reject',
                                    title:'拒绝审核',
                                    classname:'btn btn-xs btn-info btn-ajax',
                                    icon:'fa fa-close',
                                    confirm:'确认拒绝审核吗？',
                                    url:$.fn.bootstrapTable.defaults.extend.reject_url,
                                    extend: 'data-toggle=\"tooltip\" data-container=\"body\"',
                                    success: data => $(".btn-refresh").trigger("click"),
                                    visible: row => row.status == 0 ? true : false
                                },
                                {
                                    name:'revoke',
                                    title:'撤销审核',
                                    classname:'btn btn-xs btn-danger btn-ajax',
                                    extend: 'data-toggle=\"tooltip\" data-container=\"body\"',
                                    icon:'fa fa-reply',
                                    url:$.fn.bootstrapTable.defaults.extend.revoke_url,
                                    confirm:'确认要撤回审核吗？',
                                    success: data => $(".btn-refresh").trigger("click"),
                                    visible: row => (row.status == '1' || row.status == '-1') ? true : false,
                                },
                                {
                                    name:'receipt',
                                    title:'确认收货入库',
                                    classname:'btn btn-xs btn-success btn-ajax',
                                    icon:'fa fa-leaf',
                                    extend: 'data-toggle=\"tooltip\" data-container=\"body\"',
                                    confirm:'确认收货入库吗？',
                                    url: $.fn.bootstrapTable.defaults.extend.receipt_url,
                                    success: data => $(".btn-refresh").trigger("click"),
                                    visible: row => (row.status == '1') ? true : false,
                                },
                                {
                                    name:'edit',
                                    title:'编辑',
                                    classname:'btn btn-xs btn-success btn-editone',
                                    extend: 'data-toggle=\"tooltip\" data-container=\"body\"',
                                    icon:'fa fa-pencil',
                                    url: $.fn.bootstrapTable.defaults.extend.edit_url,
                                    visible: row => (row.status == '0') ? true : false,
                                },
                            ]
                        }
                    ]
                ]
            });

            $('.btn-agree').on('click', function () {
                var ids = Table.api.selectedids(table);
                
                layer.confirm('确定要审核通过吗?', { title: '审核通过', btn: ['是', '否'] },function (index) {
                    $.post($.fn.bootstrapTable.defaults.extend.agree_url, {ids: ids}, function (response) {
                        layer.close(index)

                        if(response.code) 
                        {
                            Toastr.success(response.msg)
                            $(".btn-refresh").trigger('click');
                        }else
                        {
                            Toastr.error(response.msg)
                        }
                    }, 'json')
                })
            });

            $('.btn-reject').on('click', function () {
                var ids = Table.api.selectedids(table);
                
                layer.confirm('确定要拒绝审核吗?', { title: '拒绝审核', btn: ['是', '否'] },function (index) {
                    $.post($.fn.bootstrapTable.defaults.extend.reject_url, {ids: ids}, function (response) {
                        layer.close(index)

                        if(response.code) 
                        {
                            Toastr.success(response.msg)
                            $(".btn-refresh").trigger('click');
                        }else
                        {
                            Toastr.error(response.msg)
                        }
                    }, 'json')
                })
            });

            $('.btn-revoke').on('click', function () {
                var ids = Table.api.selectedids(table);
                
                layer.confirm('确定要撤销审核吗?', { title: '撤销审核', btn: ['是', '否'] },function (index) {
                    $.post($.fn.bootstrapTable.defaults.extend.revoke_url, {ids: ids}, function (response) {
                        layer.close(index)

                        if(response.code) 
                        {
                            Toastr.success(response.msg)
                            $(".btn-refresh").trigger('click');
                        }else
                        {
                            Toastr.error(response.msg)
                        }
                    }, 'json')
                })
            });

            $('.btn-confirm').on('click', function () {
                var ids = Table.api.selectedids(table);
                
                layer.confirm('确定要入库吗?', { title: '确认入库', btn: ['是', '否'] },function (index) {
                    $.post($.fn.bootstrapTable.defaults.extend.confirm_url, {ids: ids}, function (response) {
                        layer.close(index)

                        if(response.code) 
                        {
                            Toastr.success(response.msg)
                            $(".btn-refresh").trigger('click');
                        }else
                        {
                            Toastr.error(response.msg)
                        }
                    }, 'json')
                })
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function()
        {
            //选择供应商
            $('#ModelOrder').on('show.bs.modal', function (e) {
                Controller.api.GetOrder();
            });

            $('#ModelOrder').on('hidden.bs.modal', function () {
                $('#TableOrder').bootstrapTable('destroy');
            });

            Form.api.bindevent($("form[role=form]"));
        },
        edit: function()
        {
            Controller.api.GetRegion();

            Form.api.bindevent($("form[role=form]"));
        },
        del:function()
        {
            Controller.api.bindevent();
        },
        info:function()
        {
            Controller.api.bindevent();
        },
        agree: function()
        {
            Controller.api.bindevent();
        },
        reject: function()
        {
            Controller.api.bindevent();
        },
        revoke: function()
        {
            Controller.api.bindevent();
        },
        receipt: function()
        {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () 
            {
                Form.api.bindevent($("form[role=form]"));
            },
            //订单
            GetOrder: function()
            {
                // 初始化表格参数配置
                Table.api.init({
                    extend: {
                        index_url: 'depot/async/back/order',
                        back_url: 'depot/async/back/back',
                        table: 'order',
                    }
                });
        
                var table = $("#TableOrder");
        
                // 初始化表格
                table.bootstrapTable({
                    url: $.fn.bootstrapTable.defaults.extend.index_url,
                    pk: 'id',
                    sortName: 'id',
                    toolbar: '#ToolbarOrder',
                    search: false,
                    columns: [
                    [
                        {field: 'id', title: __('ID'), sortable:true, operate: false},
                        {field: 'code', title: __('Code'), operate: 'LIKE'},
                        {field: 'amount', title: __('Amount'), sortable:true, operate:'BETWEEN'},
                        {field: 'business.nickname', title: __('Busid'), operate: 'LIKE'},
                        {field: 'express.name', title: __('Expressid'), operate: 'LIKE'},
                        {field: 'expresscode', title: __('Expresscode'), operate: 'LIKE'},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {
                            field: 'operate',
                            title: __('Operate'), 
                            table: table, 
                            events: Table.api.events.operate, 
                            formatter: Table.api.formatter.operate, 
                            buttons: [
                                {
                                    name: 'info', 
                                    text: '选择', 
                                    title: '选择', 
                                    icon: 'fa fa-magic', 
                                    classname: 'btn btn-xs btn-success btn-magic btn-ajax', 
                                    extend: 'data-toggle=\'tooltip\'',
                                    url: $.fn.bootstrapTable.defaults.extend.back_url, 
                                    success: function (data, ret) 
                                    {
                                        $('#ModelOrder').modal('hide');

                                        var order = data.order
                                        var address = data.address
                                        var product = data.product

                                        if(order)
                                        {
                                            $("#orderid").val(order.id)
                                            $("#ShowOrder").val(order.code)
                                        }

                                        Controller.api.GetAddr(address);

                                        Controller.api.GetProduct(product);
                                    }
                                }
                            ]
                        }
                    ]
                    ],
                });
        
                // 为表格绑定事件
                Table.api.bindevent(table);
            },
            //获取收货地址
            GetAddr: function (address)
            {
                $("#addrid").empty("");
                $('#addrid').selectpicker("refresh");
                var str = ''
                for(var item of address)
                {
                    var id = item.id
                    var consignee = item.consignee
                    var mobile = item.mobile
                    var region = item.region_text
                    var info = item.address
                    
                    str += `<option value="${id}">${consignee} / ${mobile} / ${region} ${info}</option>`
                }

                $("#addrid").empty("").append(str);
                $('#addrid').selectpicker("refresh");
            },
            //获取商品列表
            GetProduct: function (product)
            {
                if(!product)
                {
                    return;
                }

                var temp = ''
                for(var item of product)
                {
                    temp += `
                        <tr style="text-align: center; vertical-align: middle; ">
                            <td>${item.products.name}</td>
                            <td>${item.pronum}</td>
                            <td>${item.price}</td>
                            <td>${item.total}</td>
                        </tr>
                    `
                }

                $("#OrderProduct").append(temp);
            },
            //选择地区
            GetRegion: function ()
            {
                $("#region").on("cp:updated", function() {
                    var citypicker = $(this).data("citypicker");
                    var province = citypicker.getCode("province");
                    var city = citypicker.getCode("city");
                    var district = citypicker.getCode("district");
                    if(province)
                    {
                        $("input[name='row[province]']").val(province)
                    }

                    if(city)
                    {
                        $("input[name='row[city]']").val(city)
                    }

                    if(district)
                    {
                        $("input[name='row[district]']").val(district)
                    }
                })
            },
        }
    };
    return Controller;
});
